<?php

function deamon () {
    $pid = pcntl_fork();
    switch ($pid) {
        case -1:
            exit('进程创建错误' . PHP_EOL);
            break;
        case 0:
            $sid = posix_setsid();
            if ($sid <= 0) {
                exit('设置sid错误' . PHP_EOL);
            }
            if (chdir('/') === false) {
                exit('chdir调用错误' . PHP_EOL);
            }
            umask(0);
            fclose(STDIN);
            fclose(STDOUT);
            fclose(STDERR);
            break;
        default:
            // 父进程
            exit;
            break;
    }
}

function fork () {
    global $childs;

    $pid = pcntl_fork();
    switch ($pid) {
        case -1:
            exit('进程创建错误' . PHP_EOL);
            break;
        case 0:
            // 子进程
            while (true) {
                sleep(3);
            }
            break;
        default:
            // 父进程
            $childs[$pid] = $pid;
            break;
    }
}

deamon();

$childs = [];

$count = 3;

for ($i = 0; $i < $count; $i++) {
    fork();
}

while (count($childs) > 0) {
    $exitId = pcntl_wait($status);
    if ($exitId > 0) {
        $value = pcntl_wtermsig($status);
        unset($childs[$exitId]);
    }

    if (count($childs) < $count) {
        fork();
    }
}

